package models;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.appengine.repackaged.org.joda.time.DateTimeUtils;

import siena.Column;

import siena.Generator;
import siena.Id;
import siena.Model;
import siena.Query;

/**
 * A class that represents the last location of a user
 * 
 * @author loai
 */
public class UserLocation extends Model {

	@Id(Generator.AUTO_INCREMENT)
	public long id;
	public User user;
	public double longitude;
	public double latitude;

	Date lastSeen;

	public UserLocation(User user, double longitude, double latitude) {
		super();
		this.user = user;
		this.longitude = longitude;
		this.latitude = latitude;
		lastSeen = new Date();

	}

	public Long getId() {
		return id;
	}

	public double getLongitude() {
		return longitude;
	}

	public void setLongitude(double longitude) {
		this.longitude = longitude;
	}

	public double getLatitude() {
		return latitude;
	}

	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Date getLastSeen() {
		return lastSeen;
	}

	public void setLastSeen(Date lastSeen) {
		this.lastSeen = lastSeen;
	}

	public static Query<UserLocation> all() {
		return Model.all(UserLocation.class);
	}

	/**
	 * Updates (or create, if this is the first time) the location of the user
	 * identified by <code>phone</code> using the passed coordinates
	 * 
	 * @author loai
	 * 
	 * @param phone
	 *            the phone of the user
	 * @param longitude
	 *            the longitude of the location of the user
	 * @param latitude
	 *            the latitude of the location of the user
	 */
	public static void updateUserLocation(String phone, double longitude,
			double latitude) {
		User user = User.findByPhone(phone);
		UserLocation location = user.getLocation();
		if (location == null) {
			// create new entry if there is no such one
			location = new UserLocation(user, longitude, latitude);
			location.insert();
		} else {
			// update the current location
			location.setLatitude(latitude);
			location.setLongitude(longitude);
			location.setLastSeen(new Date());
			location.update();
		}
	}
}
